﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Collections;
using System.Windows.Forms;

using Google.GData.Client;
using Google.GData.Extensions;
using Google.GData.Spreadsheets;

namespace DataSources
{
    public class GoogleCells : IDataSource
    {
        protected SpreadsheetsService service = null;
        protected GoogleWorksheets owner = null;
        protected string ownerCurrentEntryHash;
        protected WorksheetInfo CurrentWorksheet
        {
            get
            {
                return owner.GetEntryInfo(ownerCurrentEntryHash);
            }
        }

        protected Hashtable cells = null; // TODO: remove and use only cellEntries
        protected Hashtable cellEntries = null;
        protected Size tableSize;

        public GoogleCells(SpreadsheetsService service, GoogleWorksheets owner, string ownerCurrentEntryHash)
        {
            this.service = service;
            this.owner = owner;
            this.ownerCurrentEntryHash = ownerCurrentEntryHash;

            RequestData();
        }

        private void RequestData()
        {
            if (this.CurrentWorksheet.Equals(WorksheetInfo.Empty))
                return;

            // load blocks data            
            CellQuery queryCells = new CellQuery(this.CurrentWorksheet.cellsFeedUri);
            CellFeed feedCells = this.service.Query(queryCells);
            tableSize = new Size((int)feedCells.ColCount.Count + 1, (int)feedCells.RowCount.Count + 1);

            AtomEntryCollection entries = feedCells.Entries;
            cells = new Hashtable();
            cellEntries = new Hashtable();
            for (int i = 0; i < entries.Count; ++i)
            {
                CellEntry entry = entries[i] as CellEntry;
                if (entry == null)
                    continue;

                string hash = Utils.GridCoordinate2Hash(new Point((int)entry.Cell.Column, (int)entry.Cell.Row));
                string text = entry.Cell.Value as string;
                cells.Add(hash, text);
                cellEntries.Add(hash, entry);
            }
        }

        public bool IsAuthOK()
        {
            return true;
        }

        public string GetOwnerHash()
        {
            return CurrentWorksheet.entry.Id.AbsoluteUri;
        }

        public void ReloadData()
        {
            RequestData();
        }
    }
}
